import './App.less'
import { useState, useEffect, useRef } from 'react'

const listData = new Array(10000).fill(0).map((item, index) => {
  return {
    id: index,
    name: `列表项 ${index}`
  }
})
export default function App() {
  const [startOffset, setStartOffset] = useState(0);
  const [startIndex, setStartIndex] = useState(0);
  const [endIndex, setEndIndex] = useState(0);
  const listRef = useRef(null);

  useEffect(() => {
    setEndIndex(startIndex + visibleNum);
  }, [startIndex])

  // 总列表高度
  const listHeight = listData.length * 50;
  // 可以展示的列表项数
  const visibleNum = Math.ceil(500 / 50);
  // 上方偏移量对应的 style
  const getTransform = {
    transform: `translateY(${startOffset}px)`
  }

  // 截取数据用于展示
  const showList = listData.slice(startIndex, Math.min(endIndex, listData.length));
  console.log(showList);


  const ScrollEvent = (e) => {
    // 滚动距离
    // console.log(Math.floor(listRef.current.scrollTop));
    let scrollTop = Math.floor(listRef.current.scrollTop);
    // 重新计算起始下标
    const newStartIndex = Math.floor(scrollTop / 50);
    setStartIndex(newStartIndex);
    setStartOffset(scrollTop - (scrollTop % 50));
  }

  return (
    <div className="container" onScroll={ScrollEvent} ref={listRef}>
      <div className="list-phantom" style={{ height: listHeight }}></div>
      <div className="list" style={getTransform}>
        {showList.map(item => (
          <div className="list-item" key={item.id}>
            {item.name}
          </div>
        ))}
      </div>
    </div>
  )
}
